package com.by.toolkit.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.by.toolkit.consts.GlobalConst;
import com.by.toolkit.exceptions.ServiceException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.by.toolkit.utils.ExceptionUtil.*;

/**
 * excel读数据工具类
 *
 * @author YanBingHao
 * @since 2024/9/9
 */
@Slf4j
public final class ExcelReadDataUtil {

    public static <T> List<T> readFromUrl(String excelUrl, Class<T> t, DataInfo dataInfo) {
        nullError(dataInfo, "表头信息不能为空");
        List<HeaderInfo> headers = dataInfo.getHeaders();
        nullError(headers, "表头信息不能为空");
        nullError(dataInfo.getDataClass(), "表头信息不能为空");
        // 表头名
        List<String> headerNames = headers.stream()
                .map(HeaderInfo::getHeaderName)
                .collect(Collectors.toList());
        // 字段映射
        Map<Integer, String> cellNameMap = IntStream.range(0, headers.size())
                .boxed()
                .collect(Collectors.toMap(Function.identity(), i -> headers.get(i).getDataProperty()));

        Map<Integer, Function<String, ?>> cellResolveMap = IntStream.range(0, headers.size())
                .boxed()
                .collect(Collectors.toMap(Function.identity(), i -> Objects.nonNull(headers.get(i).getDataResolver())
                        ? headers.get(i).getDataResolver()
                        : DEFAULT_STR_RESOLVER));
        List<T> datas = Lists.newArrayList();
        try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(HttpUtil.downloadBytes(excelUrl))) {
            ExcelUtil.readBySax(byteArrayInputStream, 0, (sheetIndex, rowIndex, rowCells) -> {
                // 校验表头
                if (GlobalConst.ZERO_LONG.equals(rowIndex)) {
                    if (CollectionUtils.isEmpty(rowCells)) {
                        throwError("表头信息不合法！请使用模版导入");
                    }
                    falseError(rowCells.size() == headerNames.size(), "表头信息不合法！请使用模版导入");
                    IntStream.range(0, headerNames.size())
                            .forEach(i -> {
                                String cellVal = Objects.toString(rowCells.get(i), StringUtils.EMPTY);
                                falseError(Objects.equals(cellVal, headerNames.get(i)), "表头信息不合法！请使用模版导入");
                            });
                    return;
                }
                if (CollectionUtils.isEmpty(rowCells)) {
                    log.info("[ExcelReadDataUtil][readFromUrl] rowIndex:[{}] rowCellsIsNull", rowIndex);
                    return;
                }
                Map<String, Object> dataMap = Maps.newHashMap();
                IntStream.range(0, rowCells.size())
                        .boxed()
                        .forEach(i -> {
                            String propertyName = cellNameMap.getOrDefault(i, "cell" + i);
                            String val = Objects.toString(rowCells.get(i), null);
                            Function<String, ?> function = cellResolveMap.get(i);
                            try {
                                dataMap.put(propertyName, Objects.isNull(function) ? val : function.apply(val));
                                dataMap.put("ok", true);
                            } catch (Exception e) {
                                dataMap.put(propertyName, val);
                                dataMap.put("ok", false);
                                dataMap.put("result", e.getMessage());
                            }
                        });

                log.info("[ExcelReadDataUtil][readFromUrl] rowIndex:[{}] rowCells:[{}] dataMap:[{}]", rowIndex, rowCells, dataMap);
                datas.add(BeanUtil.toBean(dataMap, t));
            });
        } catch (Exception e) {
            log.warn("[ExcelReadDataUtil][readFromUrl] hasException:[{}] ", ExceptionUtil.getStackTrace(e));
            if(e instanceof ServiceException se){
                throwError(se.getMsg());
            }
            throwError("获取excel数据异常！");
        }
        return datas;
    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class DataInfo {

        private Class<?> dataClass;

        private List<HeaderInfo> headers;

    }

    @Data
    @Builder
    @NoArgsConstructor
    @AllArgsConstructor
    public static class HeaderInfo {

        private String headerName;

        private String dataProperty;

        private Function<String, ?> dataResolver;

    }

    private static final Function<String, String> DEFAULT_STR_RESOLVER = s -> s;

}
